<?php

namespace app\api\controller\yexam;

use app\admin\command\Api;

/**
 * @ApiSector (科目)
 */

class QuestionLog extends \app\common\controller\Api
{
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle (记录用户的做题记录)
     * @ApiSummary (记录用户的做题记录)
     * @ApiSector (科目)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function questionLog()
    {
        $uid = $this->auth->id;
        $qid = $this->request->param('qid');
        $type = $this->request->param('type');
        $typeId = $this->request->param('typeId');
        $answer = $this->request->param('answer'); // 用户答案
        $question = \app\admin\model\yexam\Question::get($qid);
        if (is_null($question))
            $this->error('试题不存在');
        $log = new \app\admin\model\yexam\QuestionLog();
        $check = $log->where('type_id',$typeId)->where('user_id',$uid)->where('type',$type)->where('question_id',$qid)->find();
        if ($check)
        {
            $check->user_answer = $answer;
            $check->save();
            $this->success('修改成功');
        }
        $log->question_id = $qid;
        $log->type = $type;
        $log->type_id = $typeId;
        $log->subject_id = $question->subject_id;
        $log->user_id = $uid;
        $log->state = $question->right_answer == $answer ? 1 : 0;
        $log->user_answer = $answer;
        $log->save();
        $this->success('ok');
    }
    /**
     * @ApiTitle (清空免费试题练习记录)
     * @ApiParams (name=unit_id,type=integer,required=true,description=章节id)
     * @ApiHeaders (name=token,type=string,required=true,description=token)
     * @ApiMethod (POST)
     */
    public function emptyFreeLog(){
        $subject_id = $this->request->param("subject_id");
        $logModel = new \app\admin\model\yexam\QuestionLog();
        $logModel->where(['user_id'=>$this->auth->id,'subject_id' => $subject_id,'type' => 1])->delete();
        $this->success('清空成功！');
    }
}